import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DataServiceTest {

    // private static String applykey_url = "http://kfpttest.supnumber.cn:9011/cap/dataservice/ApplyKey.proxy";
    private static String applykey_url = "https://open.mmarket.com/cap/dataservice/ApplyKey.proxy";
    // private static String opendata_url = "http://kfpttest.supnumber.cn:9011/cap/dataservice/appDataServiceAuthen.proxy";
    private static String opendata_url = "https://open.mmarket.com/cap/dataservice/appDataServiceAuthen.proxy";
    // private static String ap_id = "752243";
    // private static String app_id = "300012473857";
    // private static String app_key = "9EBC9BCB21EBCF7BB01520D50AD8CD0D";
    private static String ap_id = "721520";
    private static String app_id = "300016379598";
    private static String app_key = "365848C0D43100E2683EC5B059878858";

    private static String client_code = "lyh_pijia";
    private static String key = "";
    private static int seq = 0;

    private static long expiryDate = -1;

    public static void main(String[] args) {

        String phone = "18321277411";
        getApplyKey();
        String requestXml = createXml(phone, "EXTLAB-AA25", "CSModelA");
        System.out.println(requestXml);
        String responseXml = doPost(opendata_url, requestXml);
        System.out.println(responseXml);
    }

    private static String doPost(String url, String xml) {
        StringBuffer respXml = new StringBuffer();
        try {
            URL u = new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(10000);
            con.setReadTimeout(10000);

            String accessName = "accessname=\"" + ap_id + "#" + app_id + "\",";

            String clientCode = "clientCode=\"" + client_code + "\",";

            String content = ap_id + "#" + app_id + "#" + app_key + "#" + getSeq();
            String code = "code=\"" + AES.encrypt(content, key) + "\",";
            String accout = "account=\"\"";
            con.setRequestProperty("Authorization", accessName + clientCode + code + accout);

            con.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
            con.connect();

            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(xml);
            osw.flush();
            osw.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                respXml.append(temp);
            }

            Map<String, List<String>> map = con.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return respXml.toString();
    }

    private synchronized static int getSeq() {
        return seq++;
    }

    private static String createXml(String phone, String servCode, String modelId) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document xml = db.newDocument();

            Element OpenDataRequest = xml.createElement("OpenDataRequest");
            Element RequestSEQ = xml.createElement("RequestSEQ");
            Element RequestTime = xml.createElement("RequestTime");
            Element APID = xml.createElement("APID");
            Element APPID = xml.createElement("APPID");
            Element ServCode = xml.createElement("ServCode");
            Element ServArgs = xml.createElement("ServArgs");

            Element EncryptPhone = xml.createElement("EncryptPhone");
            Element ModelId = xml.createElement("ModelId");
            Element Month = xml.createElement("Month");
            Element PhoneAuthCode = xml.createElement("PhoneAuthCode");

            String nowTime = getNowTime("yyyyMMddHHmmssSSS");
            RequestSEQ.setTextContent(app_id + nowTime + getSeq());
            RequestTime.setTextContent(nowTime);
            APID.setTextContent(ap_id);
            APPID.setTextContent(app_id);
            ServCode.setTextContent(servCode);

            // md5加密phone
            String md5Phone = MD5Util.getMD5(phone);
            EncryptPhone.setTextContent(md5Phone);
            ModelId.setTextContent(modelId);
            // 获取当前月份 yyyyMM
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Calendar calendar = Calendar.getInstance();
            String month = sdf.format(calendar.getTime());
            Month.setTextContent(month);
            // 生成uuid
            String uuid = java.util.UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            PhoneAuthCode.setTextContent(uuid);

            OpenDataRequest.appendChild(RequestSEQ);
            OpenDataRequest.appendChild(RequestTime);
            OpenDataRequest.appendChild(APID);
            OpenDataRequest.appendChild(APPID);
            OpenDataRequest.appendChild(ServCode);
            OpenDataRequest.appendChild(ServArgs);

            ServArgs.appendChild(EncryptPhone);
            ServArgs.appendChild(ModelId);
            ServArgs.appendChild(Month);
            ServArgs.appendChild(PhoneAuthCode);

            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer trans = transFactory.newTransformer();
            DOMSource source = new DOMSource(OpenDataRequest);
            trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            trans.transform(source, result);

            return sw.toString();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static synchronized void getApplyKey() {
        String date_format = "yyyyMMddHHmmss";
        long nowTime = Long.valueOf(getNowTime(date_format));

        if (nowTime > expiryDate) {
            String applyKeyXml = doGet(applykey_url + "?clientCode=" + client_code);
			System.out.println("applyKeyXml:");
			System.out.println(applyKeyXml);

            try {
                HashMap<String, String> applyKeyMap = parseApplyKey(applyKeyXml);
                key = applyKeyMap.get("key");
                seq = Integer.valueOf(applyKeyMap.get("seq"));
                expiryDate = Long.valueOf(addDay(String.valueOf(nowTime), date_format, 1));
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private static String addDay(String date, String format, int days) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            Date d = sdf.parse(date);
            return addDay(d, format, days);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * @param date
     * @param format
     * @param days
     * @return
     */
    private static String addDay(Date date, String format, int days) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_YEAR, days);
        return sdf.format(c.getTime());
    }

    private static HashMap<String, String> parseApplyKey(String applyKeyXml)
            throws ParserConfigurationException, SAXException, IOException, ParseException {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        InputStream is = new ByteArrayInputStream(applyKeyXml.getBytes("UTF-8"));
        Document responseDoc = docBuilder.parse(is);

        if (is != null)
            is.close();

        HashMap<String, String> applyKeyMap = new HashMap<String, String>();
        String key = getFirstNodeValue(responseDoc, "key");
        String seq = getFirstNodeValue(responseDoc, "seq");
        applyKeyMap.put("key", key);
        applyKeyMap.put("seq", seq);

        return applyKeyMap;
    }

    private static String getFirstNodeValue(Document xml, String nodeName) {
        String temp = null;
        if (xml != null) {
            NodeList nodeList = xml.getElementsByTagName(nodeName);
            if (nodeList.getLength() > 0) {
                temp = nodeList.item(0).getTextContent();
            }
        }

        return temp;
    }

    private static String doGet(String url) {
        StringBuffer respXml = new StringBuffer();
        try {
            URL u = new URL(url);
            HttpURLConnection con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setConnectTimeout(10000);
            con.setReadTimeout(10000);
            con.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String lines;
            StringBuffer response = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "UTF-8");
                response.append(lines);
            }

            reader.close();
            con.disconnect();
            respXml.append(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return respXml.toString();
    }

    private static String getNowTime(String format) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    static class AES {
        public static final String VIPARA = "0102030405060708";
        public static final String bm = "GBK";

        public static String encrypt(String cleartext, String privateKey) {
            try {
                IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());

                SecretKeySpec key = new SecretKeySpec(privateKey.getBytes(), "AES");

                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
                byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));

                return Base64.encode(encryptedData);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public static String decrypt(String encrypted, String privateKey) {
            try {
                byte[] byteMi = Base64.decode(encrypted);
                IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
                SecretKeySpec key = new SecretKeySpec(privateKey.getBytes(), "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
                byte[] decryptedData = cipher.doFinal(byteMi);

                return new String(decryptedData, bm);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    static class Base64 {
        private static char Base64Code[] = {
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
                'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', '+', '/'
        };

        private static byte Base64Decode[] = {
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                -1, -1, -1, 62, -1, 63, -1, 63, 52, 53,
                54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
                -1, 0, -1, -1, -1, 0, 1, 2, 3, 4,
                5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
                25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
                29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
                39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
                49, 50, 51, -1, -1, -1, -1, -1
        };

        private Base64() {
        }

        public static String encode(byte b[]) {
            int code = 0;
            StringBuffer sb = new StringBuffer((b.length - 1) / 3 << 6);
            for (int i = 0; i < b.length; i++) {
                code |= b[i] << 16 - (i % 3) * 8 & 255 << 16 - (i % 3) * 8;
                if (i % 3 == 2 || i == b.length - 1) {
                    sb.append(Base64Code[(code & 0xfc0000) >>> 18]);
                    sb.append(Base64Code[(code & 0x3f000) >>> 12]);
                    sb.append(Base64Code[(code & 0xfc0) >>> 6]);
                    sb.append(Base64Code[code & 0x3f]);
                    code = 0;
                }
            }

            if (b.length % 3 > 0)
                sb.setCharAt(sb.length() - 1, '=');
            if (b.length % 3 == 1)
                sb.setCharAt(sb.length() - 2, '=');

            return sb.toString();
        }

        public static byte[] decode(String code) {
            if (code == null)
                return null;

            int len = code.length();
            if (len == 0)
                return new byte[0];
            if (len % 4 != 0)
                throw new IllegalArgumentException("Base64 string length must be 4*n");

            int pad = 0;
            if (code.charAt(len - 1) == '=')
                pad++;
            if (code.charAt(len - 2) == '=')
                pad++;
            int retLen = (len / 4) * 3 - pad;
            byte ret[] = new byte[retLen];
            for (int i = 0; i < len; i += 4) {
                int j = (i / 4) * 3;
                char ch1 = code.charAt(i);
                char ch2 = code.charAt(i + 1);
                char ch3 = code.charAt(i + 2);
                char ch4 = code.charAt(i + 3);
                int tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12 | Base64Decode[ch3] << 6
                        | Base64Decode[ch4];
                ret[j] = (byte) ((tmp & 0xff0000) >> 16);
                if (i < len - 4) {
                    ret[j + 1] = (byte) ((tmp & 0xff00) >> 8);
                    ret[j + 2] = (byte) (tmp & 0xff);
                    continue;
                }
                if (j + 1 < retLen)
                    ret[j + 1] = (byte) ((tmp & 0xff00) >> 8);
                if (j + 2 < retLen)
                    ret[j + 2] = (byte) (tmp & 0xff);
            }

            return ret;
        }
    }

    static class MD5Util {
        public static String getMD5(String input) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] messageDigest = md.digest(input.getBytes());
                return convertByteToHex(messageDigest);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }

        private static String convertByteToHex(byte[] byteData) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            return sb.toString();
        }
    }
}
